#include "syscall.h"
#include "print.c"

int count=0;

void wait(){
	int lock=-1;
	int cv = -1;
	int mv = -1;
	int value;
	
	lock = CreateLock("lock",4);
	cv = CreateCondition("cv",2);
	mv = CreateMVN("mv",2,1);

	Acquire(lock);
	
	value = GetMV(mv,0);
	printf("MV value is %d\n", &value);
	value++;
	SetMV(mv,0,value);
	count++;
	Wait(cv,lock);
	value = GetMV(mv,0);
	value--;
	SetMV(mv,0,value);

	Release(lock);
	printString("leave the wait\n");


	Exit(0);

}


void main(){
	int lock=-1;
	int cv = -1;
	int mv = -1;
	int value;
	int i;
	
	lock = CreateLock("lock",4);
	cv = CreateCondition("cv",2);
	mv = CreateMVN("mv",2,1);

	for(i=0;i<5;i++)
		Fork(wait);

	while(count!=5)
		Yield();
	
	Acquire(lock);
	value = GetMV(mv,0);

	while(value!=0){
		Signal(cv,lock);
		value--;
	}

	Release(lock);

	while(1){
		
	Acquire(lock);
	value = GetMV(mv,0);
	if(value==0){
		Release(lock);
		break;
	}
	Release(lock);

	}
	

	DestroyLock(lock);
	DestroyCondition(cv);
	DestroyMVN(mv);
	
	StopServer();
	Exit(0);

}
